<template>
  <div class="all-question-container">
    <question-item
      v-for="(item, index) in questionList"
      :key="index"
      :questionInfo="item" 
      @deleteItem='deleteItem(index)'
    />
  </div>
</template>
<script>
import axios from "@/util/axios";
import {reachBottom} from '@/common/utils'

import QuestionItem from "@/components/question/QuestionItem";
export default {
  name: "AllQuestion",
  props: {
    source: {
      type: String,
      default: 'home', //通过source来辨别是主页的所有问题还是搜索页面的
    },
  },
  data() {
    return {
      questionList: [],
      pageSize: 8,
      pageNum: 1,
    };
  },
  methods: {
    //分页查询所有问题展示
    getHomeQuestion() {

      axios
        .get("question/findPage", {
          params: {
            pageSize: this.pageSize,
            pageNum: this.pageNum,
          },
        })
        .then((res) => {
          // console.log(res);
          //查询成功
          if (res.code === "1") {
            //判断是否已经到达最后一页  **unfinished
            // console.log('分页查询')
            this.pageNum++;
            this.questionList.push(...res.data);
          }
        });
    },
    //展示模糊查找的结果
    getSearchQuestion() {

      //通过路由获取查找的问题
      let q = this.$route.params.q
      axios
        .get("question/findQuestion", {
          params: {
            content: q, //通过动态路由的参数获取
            pageSize: this.pageSize,
            pageNum: this.pageNum,
          },
        })
        .then((res) => {
          // console.log(res);
          if (res.code === "1") {
            //判断是否已经到达最后一页  **unfinished
            this.pageNum++;

            this.questionList.push(...res.data);
            this.pageNum++;
          }
        });
    },
    //初始化所有问题的数据并且判断来源。
    //如果是主页，则分页查询；如果是模糊查找，则进行模糊查找结果的展示
    initial() {
      if (this.source === "home") {
        this.getHomeQuestion();
      } else {
        this.getSearchQuestion();
      }
    },
    //监听滚动条
    loadMore() {
     reachBottom(this.initial)
    },
    //删除某个问题
    deleteItem(index) {
      this.questionList.splice(index,1)
    }
  },
  mounted() {
    this.initial();
    window.addEventListener("scroll", this.loadMore);
  },
  destroyed() {
    window.removeEventListener("scroll", this.loadMore);
  },
  components: {
    QuestionItem,
  },
};
</script>

<style scoped>
.all-question-container {
  padding: 0 1.5rem;
}
</style>
